﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Borg
{
    public static class Initializer
    {
        internal static void DiscoverInitialAssemblies(TypeBuilder builder,
            IEnumerable<FileInfo> discoveryList, LogEventHandler logHandler,
            out List<ContractInfo> contracts, out List<PluginInfo> plugins)
        {
            contracts = new List<ContractInfo>();
            plugins = new List<PluginInfo>();
            IAnalyzer analyzer = new AssemblyAnalyzer(logHandler);

            foreach (var file in discoveryList.
                Where(file => !file.Name.Equals("Borg.dll") &&
                    !file.Name.Equals("Borg.Initializer.dll")))
            {
                try
                {
                    ContractInfo[] contractInfos;
                    PluginInfo[] pluginInfos;

                    if (!analyzer.AnalyzeFile(file.FullName, builder, out contractInfos, out pluginInfos))
                        continue;

                    contracts.AddRange(contractInfos);
                    plugins.AddRange(pluginInfos);
                }
                catch (Exception exception)
                {
                    logHandler(
                        Runtime.Instance,
                        new LogEventArgs(
                            MessageType.Error,
                            VerbosityLevel.Normal,
                            exception.Message));
                }
            }
        }
    }
}

